import base64
import random
import time
import string
import execjs
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse


def lesson1_1(request):
    # 目的就是检测请求头参数顺序
    # return HttpResponse("success")
    return render(request, "sec2/lesson1_1.html")


def lesson1_server_time(request):
    return HttpResponse(int(time.time() * 1000))


def lesson1_1_data_api(request):
    token = request.COOKIES.get("token")
    input_str = base64.b64decode(token).decode()
    print(str(input_str))
    key = "sec2lesson1"
    with open("myweb/static/des.js", "r", encoding="utf-8") as f:
        token = execjs.compile(f.read()).call("simplify_des", str(input_str), key)
    server_time = int(token.replace('now time: ', ""))
    # print(server_time)
    now_time = int(float(time.time()) * 1000)
    # print(now_time)
    # js_code = open("static/lesson2_cookies.js",encoding="utf-8").read()
    # ctx = execjs.compile(js_code)
    # result= ctx.call("simplify_des",input_str,key)
    # print(result)
    if abs(now_time - server_time) < 1000:
        data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        return JsonResponse({"status": 200, "data": data}, status=200)
    else:
        return JsonResponse({})


def lesson1_2(request):
    # 目的就是检测请求头参数顺序
    # return HttpResponse("success")
    return render(request, "sec2/lesson1_2.html")


def lesson1_2_data_api(request):
    token = request.session.get("set-2-1", "0")
    page = request.GET.get("page")
    sign = ""
    if "|" in token:
        sign = request.COOKIES.get(token.split("|")[0])
        token = token.split("|")[1]
    if token == sign or int(page) == 1:
        _random_num = random.randint(1, 5000)
        _cookies_key = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10))
        _cookies_value = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10))
        request.session["set-2-1"] = _cookies_key + "|" + _cookies_value
        response = JsonResponse({"code": page})
        response.set_cookie(_cookies_key, _cookies_value)
        return response
    else:
        return JsonResponse({})
    # token = request.session.get("set-2-1")
    # if token == 1000:
    #     del request.session["set-2-1"]
    #     data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    #     return JsonResponse({"status": 200, "data": data}, status=200)
    # else:
    #     return JsonResponse({})

def lesson1_3(request):
    # 目的就是检测请求头参数顺序
    # return HttpResponse("success")
    # 如果鉴权不通过,返回一段js,如果通过,则放行html页面
    with open("sec2/utils/lesson1_3_cookies_anti_spider.html","r",encoding="utf-8") as f:
        return HttpResponse(f.read())
    # return render(request, "sec2/lesson1_3.html")
